<template>
  <div class="performance-analysis">
    <!-- 页面标题 -->
    <div class="page-header mb-6">
              <h1 class="text-3xl font-bold text-gray-800">
        性能分析
      </h1>
              <p class="text-gray-600 mt-2">
        深度分析系统性能，识别瓶颈，提供优化建议
      </p>
    </div>

    <!-- 性能概览卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
      <!-- 慢查询总数 -->
      <div class="bg-white  rounded-xl shadow-lg p-6 border-l-4 border-red-500">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600 ">慢查询总数</p>
            <p class="text-3xl font-bold text-gray-900 ">
              {{ performanceStats.slowQueryCount || 0 }}
            </p>
          </div>
          <div class="p-3 bg-red-100  rounded-full">
            <svg class="w-6 h-6 text-red-600 " fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
            </svg>
          </div>
        </div>
        <div class="mt-4">
          <span class="text-red-600  text-sm font-medium">
            {{ performanceStats.avgExecutionTime || 0 }}
          </span>
          <span class="text-gray-500  text-sm ml-2">ms 平均执行时间</span>
        </div>
      </div>

      <!-- 数据库连接数 -->
      <div class="bg-white  rounded-xl shadow-lg p-6 border-l-4 border-blue-500">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600 ">数据库连接数</p>
            <p class="text-3xl font-bold text-gray-900 ">
              {{ databaseMetrics.activeConnections || 0 }}
            </p>
          </div>
          <div class="p-3 bg-blue-100  rounded-full">
            <svg class="w-6 h-6 text-blue-600 " fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4"></path>
            </svg>
          </div>
        </div>
        <div class="mt-4">
          <span class="text-blue-600  text-sm font-medium">
            {{ databaseMetrics.maxConnections || 0 }}
          </span>
          <span class="text-gray-500  text-sm ml-2">最大连接数</span>
        </div>
      </div>

      <!-- 查询缓存命中率 -->
      <div class="bg-white  rounded-xl shadow-lg p-6 border-l-4 border-green-500">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600 ">缓存命中率</p>
            <p class="text-3xl font-bold text-gray-900 ">
              {{ databaseMetrics.cacheHitRate || 0 }}%
            </p>
          </div>
          <div class="p-3 bg-green-100  rounded-full">
            <svg class="w-6 h-6 text-green-600 " fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
            </svg>
          </div>
        </div>
        <div class="mt-4">
          <span class="text-green-600  text-sm font-medium">
            {{ databaseMetrics.queryCacheSize || 0 }}
          </span>
          <span class="text-gray-500  text-sm ml-2">查询缓存大小</span>
        </div>
      </div>

      <!-- 性能评分 -->
      <div class="bg-white  rounded-xl shadow-lg p-6 border-l-4 border-purple-500">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600 ">性能评分</p>
            <p class="text-3xl font-bold text-gray-900 ">
              {{ performanceStats.performanceScore || 0 }}
            </p>
          </div>
          <div class="p-3 bg-purple-100  rounded-full">
            <svg class="w-6 h-6 text-purple-600 " fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path>
            </svg>
          </div>
        </div>
        <div class="mt-4">
          <span class="text-purple-600  text-sm font-medium">
            {{ performanceStats.optimizationCount || 0 }}
          </span>
          <span class="text-gray-500  text-sm ml-2">条优化建议</span>
        </div>
      </div>
    </div>

    <!-- 慢查询分析 -->
    <div class="bg-white  rounded-xl shadow-lg p-6 mb-8">
      <div class="flex items-center justify-between mb-6">
        <h2 class="text-xl font-semibold text-gray-800 ">慢查询分析</h2>
        <div class="flex items-center space-x-3">
          <el-button type="primary" size="small" @click="refreshSlowQueries">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
          <el-button type="success" size="small" @click="exportSlowQueries">
            <el-icon><Download /></el-icon>
            导出
          </el-button>
        </div>
      </div>

      <!-- 搜索过滤器 -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
        <el-input
          v-model="slowQueryFilters.sqlType"
          placeholder="SQL类型"
          clearable
          @keyup.enter="searchSlowQueries"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-input
          v-model="slowQueryFilters.tableName"
          placeholder="表名"
          clearable
          @keyup.enter="searchSlowQueries"
        />
        
        <el-date-picker
          v-model="slowQueryFilters.timeRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          class="w-full"
        />
        
        <el-button type="primary" @click="searchSlowQueries" :loading="searchLoading">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
      </div>

      <!-- 慢查询列表 -->
      <el-table
        :data="slowQueryList"
        style="width: 100%"
        :loading="tableLoading"
        stripe
        border
        max-height="400"
        empty-text="暂无慢查询数据"
      >
        <el-table-column prop="timestamp" label="执行时间" width="160" sortable>
          <template #default="scope">
            <span class="text-sm text-gray-600">{{ formatTime(scope.row.timestamp) }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="sqlType" label="SQL类型" width="100" />
        
        <el-table-column prop="tableName" label="表名" width="120" />
        
        <el-table-column prop="executionTime" label="执行时间(ms)" width="120" sortable>
          <template #default="scope">
            <el-tag
              :type="getExecutionTimeType(scope.row.executionTime)"
              size="small"
            >
              {{ scope.row.executionTime }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="rowsExamined" label="扫描行数" width="100" sortable />
        
        <el-table-column prop="sqlText" label="SQL语句" min-width="200">
          <template #default="scope">
            <div class="max-w-xs truncate" :title="scope.row.sqlText">
              {{ scope.row.sqlText }}
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div v-if="pagination.total > 0" class="flex justify-center mt-4">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          small
        />
          </div>

    <!-- 图表分析区域 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
      <!-- 慢查询趋势图 -->
      <div class="bg-white  rounded-xl shadow-lg p-6">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-lg font-semibold text-gray-800 ">慢查询趋势</h3>
          <el-select v-model="trendInterval" placeholder="时间间隔" size="small" class="w-32">
            <el-option label="1小时" value="1h" />
            <el-option label="1天" value="1d" />
            <el-option label="1周" value="1w" />
          </el-select>
        </div>
        <div class="h-64">
          <div ref="slowQueryTrendChart" class="w-full h-full"></div>
        </div>
      </div>

      <!-- 性能报表 -->
      <div class="bg-white  rounded-xl shadow-lg p-6">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-lg font-semibold text-gray-800 ">性能报表</h3>
          <el-select v-model="reportType" placeholder="报表类型" size="small" class="w-32">
            <el-option label="日报" value="daily" />
            <el-option label="周报" value="weekly" />
            <el-option label="月报" value="monthly" />
          </el-select>
        </div>
        <div class="h-64">
          <div ref="performanceReportChart" class="w-full h-full"></div>
        </div>
      </div>
    </div>

    <!-- 优化建议 -->
    <div class="bg-white  rounded-xl shadow-lg p-6 mb-8">
      <div class="flex items-center justify-between mb-6">
        <h2 class="text-xl font-semibold text-gray-800 ">性能优化建议</h2>
        <el-button type="primary" size="small" @click="refreshOptimizationSuggestions">
          <el-icon><Refresh /></el-icon>
          刷新建议
        </el-button>
      </div>

      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        <div
          v-for="suggestion in optimizationSuggestions"
          :key="suggestion.id"
          class="bg-gradient-to-r from-blue-50 to-indigo-50   rounded-lg p-4 border-l-4 border-blue-500"
        >
          <div class="flex items-start space-x-3">
            <div class="p-2 bg-blue-100  rounded-full">
              <svg class="w-5 h-5 text-blue-600 " fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"></path>
              </svg>
            </div>
            <div class="flex-1">
              <h4 class="font-medium text-gray-800  mb-2">
                {{ suggestion.title }}
              </h4>
              <p class="text-sm text-gray-600  mb-3">
                {{ suggestion.description }}
              </p>
              <div class="flex items-center justify-between">
                <el-tag
                  :type="getPriorityType(suggestion.priority)"
                  size="small"
                >
                  {{ suggestion.priority }}
                </el-tag>
                <span class="text-xs text-gray-500 ">
                  预计收益: {{ suggestion.estimatedBenefit }}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div v-if="optimizationSuggestions.length === 0" class="text-center py-8">
        <div class="text-gray-400 ">
          <svg class="w-16 h-16 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
          </svg>
          <p class="text-lg">暂无优化建议</p>
                    <p class="text-sm">系统运行良好，继续保持！</p>
        </div>
      </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Download } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { monitorAPI } from '~/services/api/monitor'

definePageMeta({
  layout: 'admin'
})

// 响应式数据
const performanceStats = ref({})
const databaseMetrics = ref({})
const slowQueryList = ref([])
const optimizationSuggestions = ref([])
const searchLoading = ref(false)
const tableLoading = ref(false)

// 过滤器
const slowQueryFilters = ref({
  sqlType: '',
  tableName: '',
  timeRange: null
})

// 分页
const pagination = ref({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 图表相关
const trendInterval = ref('1h')
const reportType = ref('daily')
const slowQueryTrendChart = ref(null)
const performanceReportChart = ref(null)
let slowQueryTrendChartInstance = null
let performanceReportChartInstance = null

// 获取性能统计信息
const fetchPerformanceStats = async () => {
  try {
    const response = await monitorAPI.getSlowQueryStats()
    if (response.data) {
      performanceStats.value = response.data
    }
  } catch (error) {
    console.error('获取性能统计失败:', error)
    ElMessage.error('获取性能统计失败')
  }
}

// 获取数据库性能指标
const fetchDatabaseMetrics = async () => {
  try {
    const response = await monitorAPI.getDatabaseMetrics()
    if (response.data) {
      databaseMetrics.value = response.data
    }
  } catch (error) {
    console.error('获取数据库指标失败:', error)
    ElMessage.error('获取数据库指标失败')
  }
}

// 搜索慢查询
const searchSlowQueries = async () => {
  try {
    searchLoading.value = true
    tableLoading.value = true
    
    const params = {
      pageNum: pagination.value.currentPage,
      pageSize: pagination.value.pageSize
    }
    
    if (slowQueryFilters.value.sqlType) {
      params.sqlType = slowQueryFilters.value.sqlType
    }
    if (slowQueryFilters.value.tableName) {
      params.tableName = slowQueryFilters.value.tableName
    }
    if (slowQueryFilters.value.timeRange && slowQueryFilters.value.timeRange.length === 2) {
      params.startTime = slowQueryFilters.value.timeRange[0]
      params.endTime = slowQueryFilters.value.timeRange[1]
    }
    
    const response = await monitorAPI.getSlowQueries(params)
    if (response.data) {
      slowQueryList.value = response.data.logs || []
      pagination.value.total = response.data.total || 0
    }
  } catch (error) {
    console.error('搜索慢查询失败:', error)
    ElMessage.error('搜索慢查询失败')
  } finally {
    searchLoading.value = false
    tableLoading.value = false
  }
}

// 刷新慢查询
const refreshSlowQueries = () => {
  searchSlowQueries()
}

// 导出慢查询
const exportSlowQueries = () => {
  ElMessage.success('导出功能开发中...')
}

// 获取优化建议
const fetchOptimizationSuggestions = async () => {
  try {
    const response = await monitorAPI.getOptimizationSuggestions()
    if (response.data) {
      optimizationSuggestions.value = response.data.suggestions || []
    }
  } catch (error) {
    console.error('获取优化建议失败:', error)
    ElMessage.error('获取优化建议失败')
  }
}

// 刷新优化建议
const refreshOptimizationSuggestions = () => {
  fetchOptimizationSuggestions()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.value.pageSize = size
  pagination.value.currentPage = 1
  searchSlowQueries()
}

const handleCurrentChange = (page) => {
  pagination.value.currentPage = page
  searchSlowQueries()
}

// 工具方法
const formatTime = (timestamp) => {
  if (!timestamp) return '-'
  return new Date(timestamp).toLocaleString('zh-CN')
}

const getExecutionTimeType = (time) => {
  if (time >= 1000) return 'danger'
  if (time >= 500) return 'warning'
  return 'success'
}

const getPriorityType = (priority) => {
  switch (priority) {
    case '高': return 'danger'
    case '中': return 'warning'
    case '低': return 'info'
    default: return 'info'
  }
}

// 初始化慢查询趋势图
const initSlowQueryTrendChart = () => {
  if (!slowQueryTrendChart.value) return
  
  slowQueryTrendChartInstance = echarts.init(slowQueryTrendChart.value)
  
  const option = {
    title: {
      text: '慢查询趋势分析',
      left: 'center',
      textStyle: {
        fontSize: 14,
        color: '#666'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['慢查询数量', '平均执行时间'],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00', '24:00']
    },
    yAxis: [
      {
        type: 'value',
        name: '数量',
        position: 'left'
      },
      {
        type: 'value',
        name: '时间(ms)',
        position: 'right'
      }
    ],
    series: [
      {
        name: '慢查询数量',
        type: 'line',
        smooth: true,
        data: [12, 8, 15, 22, 18, 25, 16],
        itemStyle: {
          color: '#f56c6c'
        }
      },
      {
        name: '平均执行时间',
        type: 'line',
        yAxisIndex: 1,
        smooth: true,
        data: [1200, 980, 1350, 1800, 1500, 2100, 1400],
        itemStyle: {
          color: '#e6a23c'
        }
      }
    ]
  }
  
  slowQueryTrendChartInstance.setOption(option)
}

// 初始化性能报表图
const initPerformanceReportChart = () => {
  if (!performanceReportChart.value) return
  
  performanceReportChartInstance = echarts.init(performanceReportChart.value)
  
  const option = {
    title: {
      text: '性能指标分布',
      left: 'center',
      textStyle: {
        fontSize: 14,
        color: '#666'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      bottom: 10
    },
    series: [
      {
        name: '性能指标',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '45%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 35, name: '优秀', itemStyle: { color: '#67c23a' } },
          { value: 45, name: '良好', itemStyle: { color: '#409eff' } },
          { value: 15, name: '一般', itemStyle: { color: '#e6a23c' } },
          { value: 5, name: '需优化', itemStyle: { color: '#f56c6c' } }
        ]
      }
    ]
  }
  
  performanceReportChartInstance.setOption(option)
}

// 监听图表尺寸变化
const handleResize = () => {
  if (slowQueryTrendChartInstance) {
    slowQueryTrendChartInstance.resize()
  }
  if (performanceReportChartInstance) {
    performanceReportChartInstance.resize()
  }
}

// 生命周期
onMounted(async () => {
  await Promise.all([
    fetchPerformanceStats(),
    fetchDatabaseMetrics(),
    fetchOptimizationSuggestions()
  ])
  
  await nextTick()
  initSlowQueryTrendChart()
  initPerformanceReportChart()
  
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (slowQueryTrendChartInstance) {
    slowQueryTrendChartInstance.dispose()
  }
  if (performanceReportChartInstance) {
    performanceReportChartInstance.dispose()
  }
})
</script>

<style scoped>
.performance-analysis {
  @apply min-h-screen bg-gray-50 ;
}

.page-header {
  @apply bg-white  rounded-xl shadow-lg p-6;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header h1 {
    @apply text-2xl;
  }
}

/* 图表容器样式 */
.h-64 {
  height: 16rem;
}

/* 卡片悬停效果 */
.grid > div:hover {
  @apply transform transition-all duration-200;
  transform: translateY(-2px);
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
}

/* 优化建议卡片样式 */
.from-blue-50.to-indigo-50 {
  background: linear-gradient(135deg, #eff6ff 0%, #eef2ff 100%);
}


/* 表格样式优化 */
:deep(.el-table) {
  @apply rounded-lg overflow-hidden;
}

:deep(.el-table th) {
  @apply bg-gray-50 ;
}

:deep(.el-table td) {
  @apply border-gray-200 ;
}

/* 分页样式 */
:deep(.el-pagination) {
  @apply justify-center;
}

/* 按钮样式 */
:deep(.el-button) {
  @apply rounded-lg;
}

/* 输入框样式 */
:deep(.el-input__wrapper) {
  @apply rounded-lg;
}

:deep(.el-select .el-input__wrapper) {
  @apply rounded-lg;
}

/* 日期选择器样式 */
:deep(.el-date-editor) {
  @apply rounded-lg;
}

/* 标签样式 */
:deep(.el-tag) {
  @apply rounded-md;
}

/* 图表标题样式 */
:deep(.echarts-title) {
  @apply text-gray-700 ;
}



  /* 加载状态样式 */
  .loading-overlay {
    @apply absolute inset-0 bg-white/80 flex items-center justify-center z-10;
  }

/* 空状态样式 */
.empty-state {
  @apply text-center py-12 text-gray-500 ;
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.fade-in {
  animation: fadeIn 0.5s ease-out;
}

/* 卡片动画 */
.grid > div {
  animation: fadeIn 0.5s ease-out;
}

.grid > div:nth-child(1) { animation-delay: 0.1s; }
.grid > div:nth-child(2) { animation-delay: 0.2s; }
.grid > div:nth-child(3) { animation-delay: 0.3s; }
.grid > div:nth-child(4) { animation-delay: 0.4s; }
</style>
